package com.flyan.game.motafx.ui;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.almasb.fxgl.app.scene.GameView;
import com.almasb.fxgl.dsl.FXGL;
import com.almasb.fxgl.dsl.components.EffectComponent;
import com.almasb.fxgl.entity.Entity;
import com.flyan.game.motafx.config.GameConfig;
import com.flyan.game.motafx.core.enums.ZLayerEnum;
import com.flyan.game.motafx.core.util.core.GameUtils;
import com.flyan.game.motafx.effect.BaseEffect;
import com.flyan.game.motafx.effect.npc.TransactionEffect;
import javafx.beans.property.IntegerProperty;
import javafx.geometry.Insets;
import javafx.scene.layout.Background;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontSmoothingType;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import lombok.Data;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.util.ArrayList;
import java.util.List;

/**
 * 交易页面
 *
 * @author flyan
 * @version 1.0
 * @email flyan_by_chenu@sina.com
 * @since 2025/2/10
 */
public class TransactionPage extends VBox {

    private GameView gameView;
    /**
     * 触发交易的实体
     */
    @Setter
    private Entity triggerEntity;
    private boolean isShow;
    @Setter
    private Info info;

    private final Text titleText;
    private final Text descText;
    private final VBox itemsBox;
    private final List<Text> itemBoxList = new ArrayList<>();

    /**
     * 交易页面选中选项id，默认选中第一项
     */
    private final IntegerProperty selectedItemId;

    public TransactionPage() {
        setPrefSize(GameConfig.TRANSACTION_PAGE_WIDTH, GameConfig.TRANSACTION_PAGE_HEIGHT);
        setTranslateX(GameConfig.TRANSACTION_PAGE_BEGIN_COORDINATE.getX());
        setTranslateY(GameConfig.TRANSACTION_PAGE_BEGIN_COORDINATE.getY());
        setBackground(Background.fill(Color.web("#676767")));
        selectedItemId = FXGL.getip("TransactionPage.selectedItemId");
        selectedItemId.set(0); // 默认选择第一项

        /* 标题 */
        titleText = new Text();
        titleText.setWrappingWidth(GameConfig.TRANSACTION_PAGE_WIDTH);
        titleText.setFontSmoothingType(FontSmoothingType.LCD);
        titleText.setFill(Color.WHITE);
        titleText.setTextAlignment(TextAlignment.CENTER);
        titleText.setFont(Font.font(16));
        titleText.setFill(Color.web("#ffd700"));
        getChildren().add(titleText);

        /* 交易描述 */
        descText = new Text();
        descText.setWrappingWidth(GameConfig.TRANSACTION_PAGE_WIDTH);
        descText.setFontSmoothingType(FontSmoothingType.LCD);
        descText.setFill(Color.WHITE);
        descText.setTextAlignment(TextAlignment.CENTER);
        descText.setFont(Font.font(13));
        getChildren().add(descText);

        /* 交易项 */
        itemsBox = new VBox();
        setPrefWidth(GameConfig.TRANSACTION_PAGE_WIDTH);
        itemsBox.setTranslateY((double) GameConfig.GRID_SIZE / 2);
        itemsBox.setStyle("-fx-border-color: green");
        getChildren().add(itemsBox);

        setStyle("-fx-border-color: red");
    }


    public void show() {
        if (gameView == null) {
            gameView = new GameView(this, ZLayerEnum.HIGH.getIndex());
        }

        titleText.setText(info.title);
        descText.setText(info.desc);

        /* 交易项 */
        FXGL.set("TransactionPage.itemSize", info.items.size());
        itemBoxList.clear();
        itemsBox.getChildren().clear();
        for (int i = 0; i < info.items.size(); i++) {
            String item = info.items.get(i).getName();
            Text itemText = new Text(item);
            VBox.setMargin(itemText, new Insets(0, 0, 10, 0));
            itemText.setWrappingWidth(GameConfig.TRANSACTION_PAGE_WIDTH);
            itemText.setFontSmoothingType(FontSmoothingType.LCD);
            itemText.setFill(Color.WHITE);
            itemText.setTextAlignment(TextAlignment.CENTER);
            itemText.setFont(Font.font(13));
            itemsBox.getChildren().add(itemText);
            itemBoxList.add(itemText);
        }
        Text closeItem = new Text(StrUtil.isNotEmpty(info.close) ? info.close : "离开");
        VBox.setMargin(closeItem, new Insets(0, 0, 10, 0));
        closeItem.setWrappingWidth(GameConfig.TRANSACTION_PAGE_WIDTH);
        closeItem.setFontSmoothingType(FontSmoothingType.LCD);
        closeItem.setFill(Color.WHITE);
        closeItem.setTextAlignment(TextAlignment.CENTER);
        closeItem.setFont(Font.font(13));
        closeItem.setOnMouseClicked(event -> {
            if (isShow) {
                close();
            }
        });
        itemsBox.getChildren().add(closeItem);
        itemBoxList.add(closeItem);

        /* 选中选项 */
        selectedItem(selectedItemId.get());

        /* 绑定选项选择监听器 */
        selectedItemId.addListener((obs, oldVal, newVal) -> {
            Integer selected = (Integer) newVal;
            selectedItem(selected);
        });

        FXGL.getGameScene().addGameView(gameView);
        isShow = true;
    }

    public void close() {
        FXGL.getGameScene().removeGameView(gameView);
        /* 结束勇士的交易效果 */
        GameUtils.app().braveEntityLv.get().getComponent(EffectComponent.class).endEffect(TransactionEffect.class);
        isShow = false;
    }

    /**
     * 选中选项
     *
     * @param selected 选中的选项索引
     */
    private void selectedItem(int selected) {
        for (int i = 0; i < itemBoxList.size(); i++) {
            Text item = itemBoxList.get(i);
            String itemText;
            if (i < info.items.size()) {
                itemText = info.items.get(i).getName();
            } else { // items.size 表示的是关闭选项
                itemText = StrUtil.isNotEmpty(info.close) ? info.close : "离开";
            }
            if (selected == i) {
                item.setText("* " + itemText + " *");
            } else {
                item.setText(itemText);
            }
        }
    }

    /**
     * 确认选项
     *
     * @param selected 选中的选项索引
     */
    public void enterItem(int selected) {
        if (selected == info.items.size()) {
            /* 关闭交易窗口 */
            close();
        } else {
            /* 触发交易效果 */
            Item item = info.items.get(selected);
            BaseEffect effect = ReflectUtil.newInstance(item.getEnterEffect());
            Entity brave = GameUtils.app().braveEntityLv.get();
            EffectComponent effectComponent = brave.getComponent(EffectComponent.class);
            effect.setTriggerEntity(triggerEntity);
            effect.setExtInfo("item", item);
            effectComponent.startEffect(effect);
        }
    }

    /**
     * 交易页面信息
     */
    @Data
    @Accessors(chain = true)
    public static class Info {
        private String title;
        private String desc;
        private List<Item> items;
        private String close;
    }

    /**
     * 交易项信息
     */
    @Data
    public static class Item {
        /**
         * 交易项id
         */
        private int id;
        /**
         * 交易项标题
         */
        private String name;
        /**
         * 交易项值
         */
        private int value;
        /**
         * 交易项确认触发效果
         */
        private String enterEffect;
    }

}
